package m

import (
	"GameServer/Game/dbmodule"
	"encoding/json"

	"github.com/globalsign/mgo/bson"
)

type ChatMsg struct {
	Mid  string `bson:"mid" json:"mid"`
	Uid  string `bson:"uid" json:"uid"`
	Msg  string `bson:"msg" json:"msg"`
	Ext  string `bson:"ext" json:"ext"`
	Time int64  `bson:"time" json:"time"`
	Type int64  `bson:"type" json:"type"` // 聊天消息类型 0.普通消息 1.系统消息 2.请求体力 3.玩家发红包消息 4.玩家发的红包
}

type UnionChatMsg struct {
	UnionId bson.ObjectId `bson:"_id" json:"id"`
	MsgList []*ChatMsg    `bson:"msgList" json:"msgList"`
}

func NewUnionChatMsg(id string) *UnionChatMsg {
	return &UnionChatMsg{UnionId: bson.ObjectIdHex(id), MsgList: make([]*ChatMsg, 0)}
}

func (uMsg *UnionChatMsg) GetMsgList() (r []*ChatMsg, err error) {
	err = dbmodule.MgoDB.GameDB.FindOne("unionChatMsg", bson.M{"_id": uMsg.UnionId}, nil, &uMsg)
	if err != nil {
		if err.Error() == "not found" {
			return r, nil
		}
		return
	}
	r = uMsg.MsgList
	return
}

func AddUnionChatMsg(id bson.ObjectId, msg *ChatMsg) (err error) {
	err = dbmodule.MgoDB.GameDB.Upsert("unionChatMsg", bson.M{"_id": id}, bson.M{"$push": bson.M{"msgList": bson.M{"$each": []*ChatMsg{msg}, "$slice": -500}}})
	return
}

// 删除玩家旧的体力请求数据
func DeleteUnionChatMsg(id bson.ObjectId, uid string, mid string) (err error) {
	err = dbmodule.MgoDB.GameDB.Update("unionChatMsg", bson.M{"_id": id}, bson.M{"$pull": bson.M{"msgList": bson.M{"uid": uid, "mid": mid}}})
	return
}

// 删除玩家满体力的消息
func DeleteUnionChatMsgFullEnergy(id bson.ObjectId, uid string) (err error) {
	err = dbmodule.MgoDB.GameDB.Update("unionChatMsg", bson.M{"_id": id}, bson.M{"$pull": bson.M{"msgList": bson.M{"uid": uid, "ext": "{\"type\":2,\"current\":5,\"total\":5}"}}})
	return
}

// 工会消息中 增加体力值
func UpdateUnionChatMsg(id bson.ObjectId, msg *ChatMsg) (err error) {
	err = dbmodule.MgoDB.GameDB.Update("unionChatMsg", bson.M{"_id": id, "msgList": bson.M{"$elemMatch": bson.M{"mid": msg.Mid}}}, bson.M{"$set": bson.M{"msgList.$": msg}})
	return
}

type ChatExt struct {
	Type    int64    `json:"type"` // 1.系统消息，2.体力赠送，3.提示玩家发红包，4.玩家发的红包
	LangId  int64    `json:"id,omitempty"`
	Args    []string `json:"args,omitempty"`
	Current int64    `json:"current,omitempty"`
	Total   int64    `json:"total,omitempty"`
	Goods   []BaseKV `json:"goods,omitempty"` // 红包道具列表
}

func (sMsg *ChatExt) String() (r string) {
	b, err := json.Marshal(sMsg)
	if err != nil {
		return
	}
	return string(b)
}
